import requests

url = "http://localhost:8000/chat"
params = {
    "query": "你好",
    "context": "sessionid_123"
}

# 更健壮的流式处理函数
def stream_response(response):
    buffer = b""
    for chunk in response.iter_content(chunk_size=1):
        if chunk:
            buffer += chunk
            try:
                # 尝试解码缓冲区内容
                text = buffer.decode('utf-8')
                # 成功解码后清空缓冲区
                buffer = b""
                print(text, end='', flush=True)
            except UnicodeDecodeError:
                # 如果解码失败，继续收集字节
                continue
    # 处理最后剩余的数据
    if buffer:
        try:
            print(buffer.decode('utf-8'), end='', flush=True)
        except UnicodeDecodeError:
            print(f"无法解码的数据: {buffer}")

with requests.post(url, params=params, stream=True) as response:
    stream_response(response)